<template>
  <div class="field-config-test">
    <el-card>
      <template #header>
        <h3>字段配置功能测试</h3>
      </template>
      
      <el-row :gutter="24">
        <!-- 区块选择 -->
        <el-col :span="8">
          <h4>选择测试区块</h4>
          <el-select v-model="selectedBlockId" placeholder="请选择区块" @change="loadBlockInfo">
            <el-option
              v-for="block in blocks"
              :key="block.id"
              :label="`${block.name} (${block.type})`"
              :value="block.id"
            />
          </el-select>
          
          <div v-if="selectedBlock" style="margin-top: 16px;">
            <p><strong>区块名称：</strong>{{ selectedBlock.name }}</p>
            <p><strong>区块类型：</strong>{{ selectedBlock.type }}</p>
            <p><strong>区块ID：</strong>{{ selectedBlock.id }}</p>
          </div>
          
          <div style="margin-top: 16px;">
            <el-button type="primary" @click="goToFieldConfig" :disabled="!selectedBlockId">
              配置字段
            </el-button>
          </div>
        </el-col>
        
        <!-- 字段配置预览 -->
        <el-col :span="16">
          <h4>当前字段配置</h4>
          <div v-if="fieldsLoading" style="text-align: center; padding: 20px;">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>加载字段配置中...</p>
          </div>
          
          <div v-else-if="fields.length === 0" style="text-align: center; padding: 20px;">
            <el-empty description="该区块暂无字段配置" />
            <el-button type="primary" @click="testInitDefaultFields" v-if="selectedBlock?.type">
              测试初始化默认字段
            </el-button>
          </div>
          
          <div v-else>
            <el-table :data="fields" border>
              <el-table-column prop="name" label="字段名称" width="120" />
              <el-table-column prop="label" label="字段标签" width="120" />
              <el-table-column prop="type" label="字段类型" width="100" />
              <el-table-column prop="required" label="必填" width="60">
                <template #default="{ row }">
                  <el-tag :type="row.required ? 'danger' : 'info'" size="small">
                    {{ row.required ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="orderNum" label="排序" width="60" />
              <el-table-column prop="description" label="描述" show-overflow-tooltip />
            </el-table>
            
            <div style="margin-top: 16px;">
              <el-button @click="testAddField">测试添加字段</el-button>
              <el-button type="warning" @click="testInitDefaultFields" v-if="selectedBlock?.type">
                重新初始化默认字段
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <el-divider />
      
      <!-- 默认字段模板预览 -->
      <h4>默认字段模板预览</h4>
      <el-row :gutter="24">
        <el-col :span="8" v-for="blockType in blockTypes" :key="blockType.value">
          <el-card shadow="hover" style="margin-bottom: 16px;">
            <template #header>
              <h5>{{ blockType.label }}</h5>
            </template>
            <el-button size="small" @click="previewDefaultFields(blockType.value)">
              预览默认字段
            </el-button>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 默认字段预览对话框 -->
      <el-dialog v-model="previewVisible" :title="`${previewBlockType}默认字段`" width="800px">
        <div v-if="previewFields.length === 0" style="text-align: center; padding: 40px;">
          <el-empty description="该类型暂无默认字段模板" />
        </div>
        <el-table v-else :data="previewFields" border>
          <el-table-column prop="name" label="字段名称" />
          <el-table-column prop="label" label="字段标签" />
          <el-table-column prop="type" label="字段类型" />
          <el-table-column prop="required" label="必填">
            <template #default="{ row }">
              <el-tag :type="row.required ? 'danger' : 'info'" size="small">
                {{ row.required ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" />
        </el-table>
      </el-dialog>
      
      <el-divider />
      
      <!-- 测试结果 -->
      <h4>测试结果</h4>
      <div class="test-results">
        <div v-for="(result, index) in testResults" :key="index" class="test-result">
          <el-alert
            :title="result.title"
            :type="result.type"
            :description="result.description"
            show-icon
            :closable="false"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { blockApi } from '@/api/block'

const router = useRouter()

// 响应式数据
const selectedBlockId = ref<number | null>(null)
const blocks = ref<any[]>([])
const fields = ref<any[]>([])
const fieldsLoading = ref(false)
const previewVisible = ref(false)
const previewFields = ref<any[]>([])
const previewBlockType = ref('')
const testResults = ref<any[]>([])

// 区块类型列表
const blockTypes = ref([
  { value: 'carousel', label: '轮播图' },
  { value: 'article_list', label: '文章列表' },
  { value: 'news', label: '新闻' },
  { value: 'activity', label: '活动' },
  { value: 'discussion', label: '讨论' },
  { value: 'image', label: '图片' },
  { value: 'text', label: '文本' },
  { value: 'html', label: 'HTML' },
  { value: 'video', label: '视频' },
  { value: 'list', label: '列表' },
  { value: 'custom', label: '自定义' }
])

// 计算属性
const selectedBlock = computed(() => {
  return blocks.value.find(block => block.id === selectedBlockId.value)
})

// 方法
const addTestResult = (title: string, type: 'success' | 'warning' | 'error' | 'info', description: string) => {
  testResults.value.unshift({
    title,
    type,
    description,
    time: new Date().toLocaleTimeString()
  })
  
  // 只保留最近10条结果
  if (testResults.value.length > 10) {
    testResults.value = testResults.value.slice(0, 10)
  }
}

const loadBlocks = async () => {
  try {
    const response = await blockApi.getList({ current: 1, size: 100 })
    if (response.code === 0) {
      blocks.value = response.data?.records || response.data?.list || []
      addTestResult('加载区块列表', 'success', `成功加载${blocks.value.length}个区块`)
    }
  } catch (error) {
    addTestResult('加载区块列表', 'error', '加载失败')
    ElMessage.error('加载区块列表失败')
  }
}

const loadBlockFields = async () => {
  if (!selectedBlockId.value) return
  
  fieldsLoading.value = true
  try {
    const response = await blockApi.getFields(selectedBlockId.value)
    if (response.code === 0) {
      fields.value = response.data || []
      addTestResult('加载字段配置', 'success', `成功加载${fields.value.length}个字段`)
    }
  } catch (error) {
    addTestResult('加载字段配置', 'error', '加载失败')
    ElMessage.error('获取字段配置失败')
  } finally {
    fieldsLoading.value = false
  }
}

const loadBlockInfo = () => {
  if (selectedBlockId.value) {
    loadBlockFields()
  }
}

const testInitDefaultFields = async () => {
  if (!selectedBlock.value) return
  
  try {
    const response = await blockApi.getDefaultFields(selectedBlock.value.type)
    if (response.code === 0 && response.data && response.data.length > 0) {
      addTestResult('默认字段初始化', 'success', `${selectedBlock.value.type}类型有${response.data.length}个默认字段`)
    } else {
      addTestResult('默认字段初始化', 'warning', `${selectedBlock.value.type}类型暂无默认字段模板`)
    }
  } catch (error) {
    addTestResult('默认字段初始化', 'error', '获取默认字段失败')
  }
}

const testAddField = () => {
  const newField = {
    id: `test_${Date.now()}`,
    name: `test_field_${fields.value.length + 1}`,
    label: `测试字段${fields.value.length + 1}`,
    type: 'text',
    description: '这是一个测试字段',
    required: false,
    orderNum: fields.value.length + 1
  }
  
  fields.value.push(newField)
  addTestResult('添加字段', 'info', `添加了测试字段：${newField.label}`)
}

const previewDefaultFields = async (blockType: string) => {
  try {
    const response = await blockApi.getDefaultFields(blockType)
    if (response.code === 0) {
      previewFields.value = response.data || []
      previewBlockType.value = blockTypes.value.find(t => t.value === blockType)?.label || blockType
      previewVisible.value = true
      
      addTestResult('预览默认字段', 'info', `${previewBlockType.value}类型有${previewFields.value.length}个默认字段`)
    }
  } catch (error) {
    addTestResult('预览默认字段', 'error', '获取默认字段失败')
    ElMessage.error('获取默认字段失败')
  }
}

const goToFieldConfig = () => {
  if (selectedBlockId.value) {
    router.push(`/content/block/field-config?blockId=${selectedBlockId.value}`)
  }
}

onMounted(() => {
  loadBlocks()
})
</script>

<style scoped lang="scss">
.field-config-test {
  padding: 20px;
  
  h4 {
    margin: 0 0 16px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
  
  h5 {
    margin: 0;
    color: #606266;
    font-size: 14px;
    font-weight: 600;
  }
  
  .test-results {
    .test-result {
      margin-bottom: 12px;
    }
  }
}
</style>
